'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import GlassCard from '@/components/ui/GlassCard';
import GlassButton from '@/components/ui/GlassButton';
import GlassInput from '@/components/ui/GlassInput';
import ConfirmDialog from '@/components/ui/ConfirmDialog';
import { Database, Plus, Edit, Trash2, Lock, Users, Globe, User } from 'lucide-react';
import toast from 'react-hot-toast';
import { useAuthStore } from '@/store/authStore';

interface KnowledgeBase {
  id: string;
  name: string;
  description?: string;
  visibility: string;
  owner_id?: string;
  owner_name?: string;
  document_count: number;
  created_at: string;
}

export default function KnowledgeBasePage() {
  const router = useRouter();
  const { user } = useAuthStore();
  const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);
  const [loading, setLoading] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const [editing, setEditing] = useState<KnowledgeBase | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    visibility: 'private',
  });
  const [deleteConfirm, setDeleteConfirm] = useState<{
    isOpen: boolean;
    kbId: string;
    kbName: string;
    docCount: number;
    vectorizedCount: number;
  }>({
    isOpen: false,
    kbId: '',
    kbName: '',
    docCount: 0,
    vectorizedCount: 0
  });

  useEffect(() => {
    loadKnowledgeBases();
  }, []);

  const loadKnowledgeBases = async () => {
    setLoading(true);
    try {
      const { knowledgeBaseApi } = await import('@/lib/api');
      const response = await knowledgeBaseApi.list();
      setKnowledgeBases(response.items || []);
    } catch (error: any) {
      toast.error('加载知识库失败: ' + (error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = async () => {
    if (!formData.name.trim()) {
      toast.error('请输入知识库名称');
      return;
    }

    try {
      const { knowledgeBaseApi } = await import('@/lib/api');
      await knowledgeBaseApi.create(formData);
      toast.success('创建成功！');
      setShowModal(false);
      resetForm();
      loadKnowledgeBases();
    } catch (error: any) {
      toast.error('创建失败: ' + (error.message || '未知错误'));
    }
  };

  const handleUpdate = async () => {
    if (!editing || !formData.name.trim()) return;

    try {
      const { knowledgeBaseApi } = await import('@/lib/api');
      await knowledgeBaseApi.update(editing.id, formData);
      toast.success('更新成功！');
      setShowModal(false);
      setEditing(null);
      resetForm();
      loadKnowledgeBases();
    } catch (error: any) {
      toast.error('更新失败: ' + (error.message || '未知错误'));
    }
  };

  const handleDeleteClick = async (kb: KnowledgeBase) => {
    // 检查知识库中的文档数量和向量化状态
    try {
      const { documentsApi } = await import('@/lib/api');
      const response = await documentsApi.list({ page: 1, page_size: 1000 });
      const kbDocs = response.items?.filter((doc: any) => doc.knowledge_base_id === kb.id) || [];
      const vectorizedCount = kbDocs.filter((doc: any) => doc.is_vectorized).length;
      
      setDeleteConfirm({
        isOpen: true,
        kbId: kb.id,
        kbName: kb.name,
        docCount: kbDocs.length,
        vectorizedCount
      });
    } catch (error) {
      // 如果获取文档失败，仍然允许删除，但不显示详细信息
      setDeleteConfirm({
        isOpen: true,
        kbId: kb.id,
        kbName: kb.name,
        docCount: kb.document_count,
        vectorizedCount: 0
      });
    }
  };

  const handleDeleteConfirm = async () => {
    const { kbId } = deleteConfirm;
    try {
      const { knowledgeBaseApi } = await import('@/lib/api');
      await knowledgeBaseApi.delete(kbId);
      toast.success('删除成功！');
      loadKnowledgeBases();
    } catch (error: any) {
      toast.error('删除失败: ' + (error.message || '未知错误'));
    }
  };

  const openCreateModal = () => {
    resetForm();
    setEditing(null);
    setShowModal(true);
  };

  const openEditModal = (kb: KnowledgeBase) => {
    setFormData({
      name: kb.name,
      description: kb.description || '',
      visibility: kb.visibility,
    });
    setEditing(kb);
    setShowModal(true);
  };

  const resetForm = () => {
    setFormData({
      name: '',
      description: '',
      visibility: 'private',
    });
  };

  const renderVisibilityIcon = (visibility: string) => {
    if (visibility === 'public') {
      return <Globe className="h-4 w-4" />;
    }
    if (visibility === 'shared') {
      return <Users className="h-4 w-4" />;
    }
    return <Lock className="h-4 w-4" />;
  };

  const renderVisibilityText = (visibility: string) => {
    if (visibility === 'public') {
      return '公开';
    }
    if (visibility === 'shared') {
      return '共享';
    }
    return '私有';
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">知识库</h1>
        <GlassButton onClick={openCreateModal} variant="primary" size="md">
          <Plus className="mr-2 h-4 w-4" />
          新建知识库
        </GlassButton>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {loading ? (
          <div className="col-span-full text-center py-12 text-gray-500 dark:text-white/60">
            加载中...
          </div>
        ) : knowledgeBases.length === 0 ? (
          <div className="col-span-full">
            <GlassCard className="p-12">
              <div className="text-center">
                <Database className="h-16 w-16 text-gray-400 dark:text-white/40 mx-auto mb-4" />
                <p className="text-gray-500 dark:text-white/60 mb-4">暂无知识库</p>
                <GlassButton onClick={openCreateModal} variant="primary" size="sm">
                  <Plus className="mr-2 h-4 w-4" />
                  创建第一个知识库
                </GlassButton>
              </div>
            </GlassCard>
          </div>
        ) : (
          knowledgeBases.map((kb) => {
            const isOwner = user?.id === kb.owner_id;
            return (
              <GlassCard 
                key={kb.id} 
                className="p-6 hover:shadow-lg transition-shadow relative cursor-pointer"
                onClick={() => router.push(`/dashboard/knowledge-base/${kb.id}`)}
              >
                {isOwner && (
                  <div className="absolute top-3 right-3">
                    <span className="text-xs px-2 py-1 rounded-full bg-gradient-to-r from-indigo-500 to-purple-500 text-white font-medium shadow-md">
                      我的
                    </span>
                  </div>
                )}
                {!isOwner && kb.owner_name && (
                  <div className="absolute top-3 right-3">
                    <span className="text-xs px-2 py-1 rounded-full bg-gray-200 dark:bg-white/20 text-gray-700 dark:text-white/70 font-medium flex items-center gap-1">
                      <User className="h-3 w-3" />
                      {kb.owner_name}
                    </span>
                  </div>
                )}
                
                <div className="flex items-start justify-between mb-3 pr-16">
                  <Database className="h-8 w-8 text-blue-500" />
                  {isOwner && (
                    <div className="flex gap-2">
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          openEditModal(kb);
                        }}
                        className="p-1.5 rounded-lg hover:bg-gray-200/50 dark:hover:bg-white/10 text-blue-500"
                        title="编辑"
                      >
                        <Edit className="h-4 w-4" />
                      </button>
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          handleDeleteClick(kb);
                        }}
                        className="p-1.5 rounded-lg hover:bg-red-100 dark:hover:bg-red-500/20 text-red-500"
                        title="删除"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  )}
                </div>
                <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-2">
                  {kb.name}
                </h3>
                {kb.description && (
                  <p className="text-sm text-gray-600 dark:text-white/60 mb-3 line-clamp-2">
                    {kb.description}
                  </p>
                )}
                <div className="flex items-center justify-between text-sm">
                  <div className="flex items-center gap-2 text-gray-500 dark:text-white/50">
                    {renderVisibilityIcon(kb.visibility)}
                    <span>{renderVisibilityText(kb.visibility)}</span>
                  </div>
                  <span className="text-gray-500 dark:text-white/50">
                    {kb.document_count} 文档
                  </span>
                </div>
              </GlassCard>
            );
          })
        )}
      </div>

      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
          <GlassCard className="w-full max-w-lg p-6">
            <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">
              {editing ? '编辑知识库' : '新建知识库'}
            </h2>
            <div className="space-y-4">
              <GlassInput
                label="知识库名称"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                placeholder="输入知识库名称"
              />
              <GlassInput
                label="描述（可选）"
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder="输入描述"
              />
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-white/90 mb-2">
                  可见性
                </label>
                <select
                  value={formData.visibility}
                  onChange={(e) => setFormData({ ...formData, visibility: e.target.value })}
                  className="w-full px-4 py-3 bg-white/60 dark:bg-white/10 backdrop-blur-md border border-gray-300/40 dark:border-white/20 rounded-lg text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
                >
                  <option value="private" className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">
                    私有 - 仅自己可见
                  </option>
                  <option value="shared" className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">
                    共享 - 团队成员可见
                  </option>
                  <option value="public" className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">
                    公开 - 所有人可见
                  </option>
                </select>
              </div>
              <div className="flex gap-3">
                <GlassButton
                  onClick={() => {
                    setShowModal(false);
                    setEditing(null);
                    resetForm();
                  }}
                  variant="secondary"
                  className="flex-1"
                >
                  取消
                </GlassButton>
                <GlassButton
                  onClick={editing ? handleUpdate : handleCreate}
                  variant="primary"
                  className="flex-1"
                >
                  {editing ? '更新' : '创建'}
                </GlassButton>
              </div>
            </div>
          </GlassCard>
        </div>
      )}

      {/* 删除确认对话框 */}
      <ConfirmDialog
        isOpen={deleteConfirm.isOpen}
        onClose={() => setDeleteConfirm({ isOpen: false, kbId: '', kbName: '', docCount: 0, vectorizedCount: 0 })}
        onConfirm={handleDeleteConfirm}
        title="删除知识库"
        message={
          deleteConfirm.docCount > 0
            ? `知识库"${deleteConfirm.kbName}"包含 ${deleteConfirm.docCount} 个文档${deleteConfirm.vectorizedCount > 0 ? `（其中 ${deleteConfirm.vectorizedCount} 个已向量化）` : ''}。删除知识库将同时删除所有关联文档和向量数据，此操作不可恢复。确定要删除吗？`
            : `确定要删除知识库"${deleteConfirm.kbName}"吗？`
        }
        confirmText="删除"
        cancelText="取消"
        variant="danger"
      />
    </div>
  );
}
